//
//  CalendarCollectionView.m
//  mytel
//
//  Created by KL on 17/9/8.
//  Copyright © 2017年 hf. All rights reserved.
//

#import "CalendarViewController.h"
#import "CollectionViewCell.h"
#import "DateTools.h"

@interface CalendarViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSCalendar *calendar;
    NSInteger firtDay;
    NSArray *arr;
    NSDateComponents *cmps;
    NSInteger mon;
    NSInteger mon2;
    NSInteger yearr;
    NSInteger today;
    NSInteger today2;
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,strong)UILabel *lab;

@end

@implementation CalendarViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"日历";
    CGFloat item2 = (self.view.frame.size.width-2)/2;
    NSArray *btnarr = @[@"上个月",@"下个月"];
    
    for (int j = 0; j<2; j++) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(item2*j+(j+1), 64, item2, 35)];
        [btn setTitle:btnarr[j] forState:UIControlStateNormal];
        btn.tag = 100+j;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.backgroundColor = [UIColor lightTextColor];
        
        [self.view addSubview:btn];
    }

    arr = [NSArray new];
    arr = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    CGFloat itemWidth = floor((self.view.frame.size.width-8)/7.0);
    CGFloat itemHeight = 45;
    
    for (int i = 0; i<arr.count; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((itemWidth*i)+(i+1), 100, itemWidth, 30)];
        label.backgroundColor = [UIColor whiteColor];
        
        label.textAlignment = NSTextAlignmentCenter;
        label.text = arr[i];
        [self.view addSubview:label];
    }

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(itemWidth, itemHeight);
    layout.minimumLineSpacing = 1;
    layout.minimumInteritemSpacing = 1;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 130, self.view.frame.size.width, self.view.frame.size.height-46) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CalendarDayCell"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.allowsMultipleSelection = YES;

    NSDate *now = [NSDate date];
    NSLog(@"now = %@", now);
  
    calendar = [NSCalendar currentCalendar];
   
    cmps = [calendar components: NSCalendarUnitYear|NSCalendarUnitMonth |NSCalendarUnitDay fromDate:now];
    NSLog(@"year = %ld", cmps.year);
    NSLog(@"month = %ld", cmps.month);
    NSLog(@"day = %ld", cmps.day);
    
    mon = cmps.month;
    mon2 = mon;
    yearr = cmps.year;
    today = cmps.day;
    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal) fromDate:[self dateNow:[NSString stringWithFormat:@"%ld-%ld-%d", yearr,mon2,1]]];
    firtDay = [comp weekday] - 1;
    
    NSLog(@"first is %ld",[comp weekday]);
    
    _lab = [[UILabel alloc]initWithFrame:CGRectMake(280,450, 100,25)];
    _lab.text = _lab.text = [NSString stringWithFormat:@"现在是%ld月。",mon];
    _lab.textColor = [UIColor blueColor];
    _lab.backgroundColor = [UIColor whiteColor];
    
    [_collectionView addSubview:_lab];

    [self.view addSubview:_collectionView];
}

- (void)btnClick:(UIButton *)btn
{
    if (btn.tag == 100) {
        NSLog(@"woi znxclkzxmc;lk");
        dispatch_async(dispatch_get_main_queue(), ^{
            mon2 = mon2 - 1;
            NSDateComponents *com = [[NSCalendar currentCalendar] components:(NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal) fromDate:[self dateNow:[NSString stringWithFormat:@"%ld-%ld-%d", yearr,mon2,1]]];
            NSInteger first = [com weekday] - 1;
            firtDay = first;
            _lab.text = [NSString stringWithFormat:@"现在是%ld月。",mon2];
            today2 = today;
            [_collectionView reloadData];
        });
    
    }
    else
    {
         NSLog(@"mojml;jmkl;jm;lk");
        dispatch_async(dispatch_get_main_queue(), ^{
            mon2 = mon2 + 1;
            NSDateComponents *com = [[NSCalendar currentCalendar] components:(NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal) fromDate:[self dateNow:[NSString stringWithFormat:@"%ld-%ld-%d", yearr,mon2,1]]];
            NSInteger first = [com weekday] - 1;
            firtDay = first;
            _lab.text = [NSString stringWithFormat:@"现在是%ld月。",mon2];
            today2 = today;
            [_collectionView reloadData];
        });
    }
}

- (NSDate *)dateNow:(NSString *)date{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date_ = [formatter dateFromString:date];
    return date_;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[self dateNow:[NSString stringWithFormat:@"%ld-%ld-%d", cmps.year,mon2,1]]].length + firtDay;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarDayCell" forIndexPath:indexPath];
    cell.label.textColor = [UIColor blueColor];
    if (indexPath.item < firtDay)
    {
        cell.label.text = @"";
    }
    else
    {
        cell.label.text = [NSString stringWithFormat:@"%ld",(indexPath.item+1)-firtDay];
        if ((indexPath.item+1)-firtDay == today) {
            cell.backgroundColor = [UIColor orangeColor];
        }
    }
    return cell;
}


@end
